package norbert.logs {
	import mx.core.Application;
	import mx.core.IMXMLObject;
	import mx.logging.Log;
	import mx.logging.LogEvent;
	import mx.logging.LogEventLevel;
	import mx.logging.targets.LineFormattedTarget;

	public class ApplicationTarget extends LineFormattedTarget implements IMXMLObject {
		public function ApplicationTarget() {
			level = LogEventLevel.ALL;
			Log.addTarget(this);
		}
		
		private var lastEventDate: Date;
		
		private function toTwoDigit(num: uint): String {
			return (num < 10 ? "0" : "") + num;
		}
		
		override public function logEvent(event: LogEvent): void {
			var eventDate: Date = new Date();
			
			var app: Application = Application.application as Application;
			if (app.data == null) {
				app.data = "";
			}
			
			if (lastEventDate && eventDate.getTime() - lastEventDate.getTime() > 3000) {
				var seconds: uint = (eventDate.getTime() - lastEventDate.getTime()) / 1000;
				app.data += "\n(Delay: " + toTwoDigit(Math.round(seconds / 60)) + ":" + toTwoDigit(seconds % 60) + ")\n\n";
			}
			
			lastEventDate = eventDate;
			
			app.data += event.message + "\n";
		}
	}
}
